/**
 * create by young (young2f@outlook.com) on 2023/4/16
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');
const _stringUtils = require('../utils/stringUtils');
const table = 'OutboundOrder';
const moment = require('moment');
module.exports = class extends base {

  /**
   * 创建出货记录
   * @param body
   * @returns {Promise<{result: *, status: string}>}
   */
  async createOutboundLot(body) {
    const { ctx, service } = this;
    const {
      tenantCode,
      salesOrderCode,
      tenantName,
      createUser,
      createUsername,
      createdTs,
      lotCode
    } = body;
    if (!lotCode) {
      body.lotType = 'OUT' + moment()
        .format('YYYYMMDDHHmmss');
    }

    const order = await ctx.app.dbs.findOne('SalesOrder', { tenantCode, code: salesOrderCode });
    const { customer, customerCode, } = order;

    /**
     * 创建商品的出货记录
     */
    const result = await ctx.app.dbs.insert('OutboundLot', { ...body, customer, customerCode });

    /**
     * 保存历史操作记录
     * @type {{table: string, name: string, oldData, tenantCode, code, tenantName, createUser, createUsername, createdTs}}
     */
    const history = {
      table: 'SalesOrder',
      name: '订单创建出货记录',
      oldData: body,
      tenantCode,
      code: salesOrderCode,
      tenantName,
      createUser,
      createUsername,
      createdTs
    };
    const historyRes = await ctx.app.dbs.insert('History', history);
    return { status: 'ok', result };
  }

  /**
   * 查询出货记录
   * @param body
   * @returns {Promise<{result: *, status: string}>}
   */
  async findOutboundLots(body) {
    const { ctx } = this;
    console.log('find out lots', body);
    const { customer, prodName, prodCode, salesOrderCode, lotType, tenantCode,spLotId } = body;
    const query = { tenantCode };
    if (spLotId) query['spLotId'] = { $regex: spLotId };
    if (customer) query['customer'] = { $regex: customer };
    if (prodName) query['prodName'] = { $regex: prodName };
    if (prodCode) query['prodCode'] = { $regex: prodCode };
    if (salesOrderCode) query['salesOrderCode'] = { $regex: salesOrderCode };
    if (lotType) query['lotType'] = { $regex: lotType };
    query['isDeleted'] = false;
    const result = await ctx.app.dbs.find('OutboundLot', query);
    return { status: 'ok', result };
  }

  /**
   * 删除出货记录
   * @param body
   * @returns {Promise<{result: *, status: string}>}
   */
  async deleteOutboundLot(body) {
    const { ctx } = this;
    const {
      lotCode,
      code,
      tenantCode,
      outboundCount, price,
      salesOrderCode,
      tenantName,
      createUser,
      createUsername,
      createdTs, spLotId,
    } = body;
    console.log('deleteOutboundLot body', body);
    /**
     * 出库是产品出库，所以要通过产品ID拿到原料和包材数据
     */
    const result = await ctx.app.dbs.deleteOne('OutboundLot', { lotCode, tenantCode });

    const history = {
      table: 'SalesOrder',
      name: '订单删除出货记录',
      oldData: body,
      tenantCode,
      code: salesOrderCode,
      tenantName,
      createUser,
      createUsername,
      createdTs
    };
    const historyRes = await ctx.app.dbs.insert('History', history);
    return { status: 'ok' };
  }


  // async findShippingFeeMany(body) {
  //   const { ctx } = this;
  //   console.log('find shippingFeeMany', body);
  //   const { shippingMan } = body;
  //   if (shippingMan) {
  //     body.shippingMan = { $regex: shippingMan };
  //   }
  //   const list = await ctx.app.dbs.find('ShippingFee', body);
  //   let fee = 0,
  //     _count = 0,
  //     payment = 0;
  //   _.map(list, item => {
  //     const { shippingFee = 0, count = 0, paymentAmount = 0 } = item;
  //     fee += shippingFee;
  //     _count += count;
  //     payment += paymentAmount;
  //   });
  //   return { status: 'ok', result: { list, fee, count: _count, payment } };
  // }
  //
  // // async updateShippingFee(body) {
  //   const { ctx } = this;
  //   const { lotCode, tenantCode, shippingFee } = body;
  //   const result = await ctx.app.dbs.updateOne('OutboundLot', { lotCode, tenantCode }, body);
  //   const result1 = await ctx.app.dbs.updateOne('ShippingFee', { lotCode, tenantCode }, body);
  //   return { status: 'ok', result };
  // }

  // async createShippingFee(body) {
  //   const { ctx } = this;
  //   console.log('updateShippingFeeMany createShippingFee', body);
  //   const {
  //     code = 'SPF' + Date.now()
  //       .valueOf()
  //   } = body;
  //   const result = await ctx.app.dbs.insert('ShippingFee', body);
  //   return { status: 'ok', result };
  // }
  //
  // async deleteShippingFee(body) {
  //   const { ctx } = this;
  //   console.log('deleteShippingFee shippingFeeMany', body);
  //   const { tenantCode, code } = body;
  //   const result = await ctx.app.dbs.deleteOne('ShippingFee', { code, tenantCode });
  //   return { status: 'ok', result };
  // }

  async procureReturnOfGoodsOutbound(body) {
    const { ctx } = this;
    const { orderCode, tenantCode, code, returnCount, } = body;

    //回写采购退货单的出库
    const result1 = await ctx.app.dbs.updateOne('ProcureMaterialReturnOrder', {
      orderCode,
      tenantCode
    }, { outboundCount: returnCount });
    console.log('退货出库', orderCode, returnCount, tenantCode, result1);

    /**
     *   todo 采购退货的出库流程
     */

    /**
     * 扣库存
     */
    const result = await ctx.app.dbs.updateOne('Material', {
      code,
      tenantCode
    }, { $inc: { storeCount: -returnCount } });
    /**
     * 创建出库批次记录
     */
    body.lotType = '采购物料退货出库';
    body.lotCode = 'OLT' + moment()
      .format('YYYYMMDDHHmmss');
    body.outboundCount = returnCount;
    body.returnCode = orderCode;
    const res1 = await ctx.app.dbs.insert('OutboundLot', body);
    return { status: 'ok', result };
  }
};
